import * as React from 'react';
import { connect } from 'react-redux';

/**
 * connect包裹组件生成
 * eg:
 * makeHoc(function(state){
 * })(Component, {
 *  method1() {
 *    //TODO
 *  },
 *  method2() {
 *    //TODO
 *  }
 * })
 * @param {function} mapStateToProps read data from reducer.
 * @param {function} mapDispatchToProps read data from reducer.
 * @param {function} mergeProps read data from reducer.
 *
 * @returns {Function} Easily call methods.
 */
export default function makeHoc(mapStateToProps: any, mapDispatchToProps?: any, mergeProps?: any) {
  return function(Component: any, reopen: any) {
    const ConnectComponent = connect(mapStateToProps, mapDispatchToProps, mergeProps, {
      withRef: true,
    })(Component);

    class MakeHocWrapper extends React.Component {
      innerComponent: any;
      componentDidMount() {
        Object.keys(reopen).forEach((method: any) => {
          (this as any)[method] = reopen[method].bind(this.innerComponent.wrappedInstance);
        });
      }

      render() {
        return (
          <ConnectComponent
            {...this.props}
            ref={editAttachment => {
              this.innerComponent = editAttachment;
            }}
          />
        );
      }
    }

    return MakeHocWrapper;
  };
}
